﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace TransformerManager.WPF.Common.Helper
{
    public static class EnumExtension
    {
        public static string GetDescription(this Enum value)
        {
            return value.GetType()
                .GetMember(value.ToString())
                .FirstOrDefault()?
                .GetCustomAttribute<DescriptionAttribute>()?
                .Description;
        }

        public static T GetEnumByDescr<T>(string description)
        {
            Type enumType = typeof(T);
            foreach (FieldInfo field in enumType.GetFields())
            {
                DescriptionAttribute[] curAttrs = (DescriptionAttribute[])field.GetCustomAttributes(typeof(T), true);
                if (curAttrs != null && curAttrs.Length > 0)
                {
                    if (curAttrs[0].Description == description)
                        return (T)field.GetValue(null);
                }
                else
                {
                    if (field.Name == description)
                        return (T)field.GetValue(null);
                }
            }
            throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
        }
    }
}
